<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="桶编号" prop="tankCode">
        <el-select
            v-model="queryParams.tankCode"
            placeholder="请选择桶编号"
            clearable
            style="width: 180px"
            @change="handleQuery"
        >
          <el-option
              v-for="item in tankOptions"
              :key="item.tankCode"
              :label="item.tankCode"
              :value="item.tankCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="巡查时间" style="width: 308px">
        <el-date-picker
            v-model="daterangeInspectionTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="巡查人" prop="inspector">
        <el-input
            v-model="queryParams.inspector"
            placeholder="请输入巡查人"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['SysWaterQuality:SysWaterQualityInspection:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['SysWaterQuality:SysWaterQualityInspection:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['SysWaterQuality:SysWaterQualityInspection:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['SysWaterQuality:SysWaterQualityInspection:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="SysWaterQualityInspectionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="养殖桶编号" align="center" prop="tankCode" :show-overflow-tooltip="true"/>
      <el-table-column label="巡查时间" align="center" prop="inspectionTime" width="150">
        <template #default="scope">
          <span>{{ parseTime(scope.row.inspectionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="巡查人" align="center" prop="inspector" width="70px" />
      <el-table-column label="水温 (°C)" align="center" prop="temperature" />
      <el-table-column label="盐度" align="center" prop="salinity"  width="70px" />
      <el-table-column label="pH值" align="center" prop="ph" />
      <el-table-column label="溶氧 (mg/L)" align="center" prop="dissolvedOxygen" />
      <el-table-column label="氨氮 (mg/L)" align="center" prop="ammoniaNitrogen" />
      <el-table-column label="亚硝酸盐 (mg/L)" align="center" prop="nitrite" />
      <el-table-column label="异常描述" align="center" prop="anomalyDescription" width="150">
        <template #default="scope">
          <span class="ellipsis" :title="scope.row.anomalyDescription">{{ scope.row.anomalyDescription }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks" width="150">
        <template #default="scope">
          <span class="ellipsis" :title="scope.row.remarks">{{ scope.row.remarks }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片上传" align="center" prop="imageUrls" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.imageUrls" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['SysWaterQuality:SysWaterQualityInspection:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['SysWaterQuality:SysWaterQualityInspection:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改水质巡查记录对话框 -->
    <el-dialog :title="title" v-model="open" width="680px" append-to-body>
      <el-form ref="SysWaterQualityInspectionRef" :model="form" :rules="rules" label-width="80px" class="form-justify">
        <el-row :gutter="20">
          <el-col :span="12">
        <el-form-item label="养殖桶" prop="tankId">
          <el-select v-model="form.tankId" placeholder="请选择桶编号">
            <el-option
                v-for="item in tankOptions"
                :key="item.id"
                :label="item.tankCode"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="巡查人" prop="inspector">
              <el-input v-model="form.inspector" placeholder="请输入巡查人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="水温" prop="temperature">
              <el-input v-model="form.temperature" placeholder="请输入水温 (°C)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="盐度" prop="salinity">
              <el-input v-model="form.salinity" placeholder="请输入盐度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="溶氧" prop="dissolvedOxygen">
              <el-input v-model="form.dissolvedOxygen" placeholder="请输入溶氧 (mg/L)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="氨氮" prop="ammoniaNitrogen">
              <el-input v-model="form.ammoniaNitrogen" placeholder="请输入氨氮 (mg/L)" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="pH值" prop="ph">
              <el-input v-model="form.ph" placeholder="请输入pH值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="亚硝酸盐" prop="nitrite">
              <el-input v-model="form.nitrite" placeholder="请输入亚硝酸盐 (mg/L)" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="巡查时间" prop="inspectionTime">
          <el-date-picker clearable
                          v-model="form.inspectionTime"
                          type="date"
                          style="width: 235px"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择巡查时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="异常描述" prop="anomalyDescription">
          <el-input v-model="form.anomalyDescription" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" :rows="3" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="图片上传" prop="imageUrls">
          <image-upload v-model="form.imageUrls"/>
<!--          <el-button type="primary" @click="analyzeData" style="margin-left: 10px; margin-top: 8px;">分析数据</el-button>-->
        </el-form-item>
        <el-button type="primary" @click="analyzeData" style="width: 100px;margin-left: 80px;margin-top: -10px">分析数据</el-button>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SysWaterQualityInspection">
import { listSysWaterQualityInspection, getSysWaterQualityInspection, delSysWaterQualityInspection, addSysWaterQualityInspection, updateSysWaterQualityInspection,analyzeWaterQuality } from "@/api/SysWaterQuality/SysWaterQualityInspection"
import { listSysTanks } from "@/api/SysTanks/SysTanks"
import { onMounted, watch, ref, reactive, toRefs, getCurrentInstance } from 'vue'
import { useRoute } from 'vue-router'

const { proxy } = getCurrentInstance()
const tankOptions = ref([])
const SysWaterQualityInspectionList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const daterangeInspectionTime = ref([])
const route = useRoute()

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tankId: null,
    tankCode: null,
    inspectionTime: null,
    inspector: null,
    temperature: null,
    salinity: null,
    ph: null,
    dissolvedOxygen: null,
    ammoniaNitrogen: null,
    nitrite: null,
    anomalyDescription: null,
    imageUrls: null,
    remarks: null,
  },
  rules: {
    tankId: [
      { required: true, message: "养殖桶ID不能为空", trigger: "blur" }
    ],
    inspectionTime: [
      { required: true, message: "巡查时间不能为空", trigger: "blur" }
    ],
    inspector: [
      { required: true, message: "巡查人不能为空", trigger: "blur" }
    ],
    // 修改水温验证规则 - 使用正则表达式
    temperature: [
      { required: true, message: "水温不能为空", trigger: "blur" },
      { pattern: /^([1-9]\d{0,2}|0)(\.\d{1,1})?$/, message: "水温必须为数字，最多3位整数，1位小数", trigger: "blur" }
    ],
    // 修改盐度验证规则 - 使用正则表达式
    salinity: [
      { required: true, message: "盐度不能为空", trigger: "blur" },
      { pattern: /^([1-9]\d{0,2}|0)(\.\d{1,1})?$/, message: "盐度必须为数字，最多3位整数，1位小数", trigger: "blur" }
    ],
    // 修改pH值验证规则 - 使用正则表达式
    ph: [
      { required: true, message: "pH值不能为空", trigger: "blur" },
      { pattern: /^(0|[1-9]\d?)(\.\d{1,1})?$/, message: "pH值必须为0~99之间的数字，最多1位小数", trigger: "blur" }
    ],
    // 修改溶氧验证规则 - 使用正则表达式
    dissolvedOxygen: [
      { required: true, message: "溶氧不能为空", trigger: "blur" },
      { pattern: /^([1-9]\d{0,2}|0)(\.\d{1,1})?$/, message: "溶氧必须为数字，最多3位整数，1位小数", trigger: "blur" }
    ],
    // 修改氨氮验证规则 - 使用正则表达式
    ammoniaNitrogen: [
      { required: true, message: "氨氮不能为空", trigger: "blur" },
      { pattern: /^([1-9]\d{0,1}|0)(\.\d{1,2})?$/, message: "氨氮必须为数字，最多2位整数，2位小数", trigger: "blur" }
    ],
    // 修改亚硝酸盐验证规则 - 使用正则表达式
    nitrite: [
      { required: true, message: "亚硝酸盐不能为空", trigger: "blur" },
      { pattern: /^([1-9]\d{0,1}|0)(\.\d{1,2})?$/, message: "亚硝酸盐必须为数字，最多2位整数，2位小数", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询水质巡查记录列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangeInspectionTime && '' != daterangeInspectionTime) {
    queryParams.value.params["beginInspectionTime"] = daterangeInspectionTime.value[0]
    queryParams.value.params["endInspectionTime"] = daterangeInspectionTime.value[1]
  }
  listSysWaterQualityInspection(queryParams.value).then(response => {
    SysWaterQualityInspectionList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    tankId: null,
    inspectionTime: null,
    inspector: null,
    temperature: null,
    salinity: null,
    ph: null,
    dissolvedOxygen: null,
    ammoniaNitrogen: null,
    nitrite: null,
    anomalyDescription: null,
    imageUrls: null,
    remarks: null,
    status: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("SysWaterQualityInspectionRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeInspectionTime.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加水质巡查记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getSysWaterQualityInspection(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改水质巡查记录"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["SysWaterQualityInspectionRef"].validate(valid => {
    if (valid) {
      // 确保所有数值都是数字类型
      form.value.temperature = Number(form.value.temperature)
      form.value.salinity = Number(form.value.salinity)
      form.value.ph = Number(form.value.ph)
      form.value.dissolvedOxygen = Number(form.value.dissolvedOxygen)
      form.value.ammoniaNitrogen = Number(form.value.ammoniaNitrogen)
      form.value.nitrite = Number(form.value.nitrite)
      form.value.tankId = Number(form.value.tankId)
      if (form.value.id != null) {
        updateSysWaterQualityInspection(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addSysWaterQualityInspection(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除水质巡查记录编号为"' + _ids + '"的数据项？').then(function() {
    return delSysWaterQualityInspection(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('SysWaterQuality/SysWaterQualityInspection/export', {
    ...queryParams.value
  }, `SysWaterQualityInspection_${new Date().getTime()}.xlsx`)
}

getList()

function getTankOptions() {
  listSysTanks({ pageNum: 1, pageSize: 1000 })
      .then(response => {
        // 添加 handleResponse 函数的定义
        const handleResponse = (response) => {
          // 检查是否为标准响应格式
          if (response && typeof response === 'object') {
            // 如果有code字段且不为200，视为错误
            if ('code' in response && response.code !== 200) {
              throw new Error(response.msg || '接口请求失败');
            }
            // 返回数据部分，优先取data字段
            return response.data !== undefined ? response.data : response;
          }
          return response;
        };

        const data =handleResponse(response);
        tankOptions.value = data.rows || [];
      })
      .catch(err => {
        proxy.$modal.msgError("加载桶列表失败: " + (err.message || err));
        console.error("加载桶列表错误:", err);
      });
}

onMounted(async () => {
  await getTankOptions(); // 确保桶列表加载出来

  if (route.query.tankCode) {
    queryParams.value.tankCode = route.query.tankCode;   // 自动填充下拉框
    const tank = tankOptions.value.find(t => t.tankCode === route.query.tankCode);
    if (tank) {
      queryParams.value.tankId = tank.id;                // 传给后端过滤用
    }
  }

  queryParams.value.pageNum = 1;
  getList(); // 直接拉取列表
})

async function analyzeData() {
  try {
    // 创建loading实例并保存引用
    const loadingInstance = proxy.$loading({
      lock: true,
      text: '正在分析水质数据...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    // 调用已有的 analyzeWaterQuality 函数而不是直接 fetch
    const result = await analyzeWaterQuality({
      temperature: form.value.temperature,
      salinity: form.value.salinity,
      ph: form.value.ph,
      dissolvedOxygen: form.value.dissolvedOxygen,
      ammoniaNitrogen: form.value.ammoniaNitrogen,
      nitrite: form.value.nitrite
    });

    // 关闭loading实例
    loadingInstance.close();

    // 将分析结果填入异常描述和备注字段
    if (result.data && result.data.improvementSuggestions) {
      // 填入异常描述
      const waterStability = result.data.waterStability;
      form.value.anomalyDescription = waterStability ? `${String(waterStability)}` : '';

      // 填入备注
      const seahorseHealth = result.data.seahorseHealth + result.data.improvementSuggestions;
      form.value.remarks = seahorseHealth !== undefined && seahorseHealth !== null ?
        `${String(seahorseHealth)}` : '水质稳定性：未知';
    } else {
      // 如果没有返回预期格式的数据，使用原始数据
      form.value.anomalyDescription = JSON.stringify(result.data || result);
      form.value.remarks = '';
    }
    proxy.$modal.msgSuccess("数据分析成功");
  } catch (error) {
    // 关闭loading实例
    proxy.$loading.close();
    proxy.$modal.msgError("数据分析失败: " + error.message);
  }
}
</script>

<style scoped>
.form-justify {
  display: flex;
  flex-direction: column;
  align-items: stretch;
}

.form-justify .el-form-item {
  width: 100%;
  margin-bottom: 16px;
}

.form-justify .el-form-item__label {
  text-align: left;
}

.form-justify .el-form-item__content {
  display: flex;
  justify-content: space-between;
}

/* 添加新的样式类 */
.ellipsis {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}
</style>


